package cn.chenhao.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 自定义拦截器
 * 写一个拦截器类，实现HandlerInterceptor接口，重写preHandle方法
 *  @ Component：意思是将拦截器类交给spring管理
 *
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");// 通过请求头，获取token
        if(!StringUtils.isEmpty(token)){// 如果token不为空
            Object o = redisTemplate.opsForValue().get(token);
            if(o != null){
                redisTemplate.opsForValue().set(token,o,30, TimeUnit.MINUTES);
                return true;
            }
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        // {"success":false,"message":"noLogin"}  在外面写好拷贝进去
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.close();
        return false;
    }
}
